package web.servlet;

import com.alibaba.fastjson.JSONObject;
import com.rdc.example.bean.PageBean;
import com.rdc.example.bean.Result;
import com.rdc.example.bean.dto.PlayListDTO;
import com.rdc.example.bean.dto.SongDTO;
import com.rdc.example.bean.dto.UserDTO;
import com.rdc.example.service.PlayListService;
import com.rdc.example.service.SongService;
import com.rdc.example.service.UserService;
import com.rdc.example.service.impl.PlayListServiceImpl;
import com.rdc.example.service.impl.SongServiceImpl;
import com.rdc.example.service.impl.UserServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/playList/*")
@MultipartConfig
public class PlayListServlet extends BaseServlet{
    PlayListService playListService = new PlayListServiceImpl();
    SongService songService = new SongServiceImpl();

    public void send(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JSONObject.toJSONString("playList"));
    }


    public void getPlayListByUserId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        System.out.println("getPlayListByUserId...");
        //接收 当前页码 和 每页展示条数  eg: url?currentPage=1&pageSize=5
        Integer currentPage = Integer.parseInt(req.getParameter("currentPage"));
        Integer pageSize = Integer.parseInt(req.getParameter("pageSize"));
        //在session中获取userId
        HttpSession session = req.getSession();
        Integer userId=((UserDTO) session.getAttribute("userDTO")).getId();
        //调用service
        PageBean<PlayListDTO> pageBean = playListService.getPlayListListByUserId(userId, currentPage, pageSize);
        //json发送
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JSONObject.toJSONString(pageBean));
    }

    public void listSongIdListOutPlayListId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        System.out.println("listSongIdListOutPlayListId...");
        //接收 当前页码 和 每页展示条数
        Integer currentPage = Integer.parseInt(req.getParameter("currentPage"));
        Integer pageSize = Integer.parseInt(req.getParameter("pageSize"));
        Integer playListId = Integer.parseInt(req.getParameter("playListId"));
        //在session中获取userId
        HttpSession session = req.getSession();
        Integer userId=((UserDTO) session.getAttribute("userDTO")).getId();
        //调用service
        PageBean<SongDTO> pageBean= songService.listSongIdListOutPlayListId(playListId, currentPage, pageSize);
        //json发送
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JSONObject.toJSONString(pageBean));
    }

    public void listSongIdListByPlayListId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        System.out.println("listSongIdListByPlayListId...");
        //接收 当前页码 和 每页展示条数
        Integer currentPage = Integer.parseInt(req.getParameter("currentPage"));
        Integer pageSize = Integer.parseInt(req.getParameter("pageSize"));
        Integer playListId = Integer.parseInt(req.getParameter("playListId"));
        //在session中获取userId
        HttpSession session = req.getSession();
        Integer userId=((UserDTO) session.getAttribute("userDTO")).getId();
        //调用service
        PageBean<SongDTO> pageBean= songService.getSongListByPlayListId(playListId, currentPage, pageSize);
        //json发送
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JSONObject.toJSONString(pageBean));
    }

    public void  turnInOrOutPlaylist(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        System.out.println("turnInOrOutPlaylist...");
        // playListId: this.selectedPlaylistId,
        //                    songId: song.id
        Integer playListId = Integer. parseInt(req.getParameter("playListId"));
        Integer songId = Integer.parseInt(req.getParameter("songId"));
        //调用service
        Result result= playListService.turnInOrOutPlaylist(playListId, songId);
        System.out.println(result);
        //json发送
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JSONObject.toJSONString(result));
    }

    public void addPlayList(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        System.out.println("addPlayList...");
        //获取信息
        resp.setContentType("application/json;charset=utf-8");
        //创建DiskFileItemFactory工厂对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //设置文件缓存目录，如果该文件夹不存在则创建一个
        File file = new File("D:\\TempFolder");
        if (!file.exists()) {
            file.mkdirs();
        }
        factory.setRepository(file);
        //创建ServletFileUpload对象
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        //设置字符编码
        fileUpload.setHeaderEncoding("utf-8");
        //解析request，获取FileItem对象
        List<FileItem> fileItems = fileUpload.parseRequest(req);
        //获取信息 使用map储存,再读出来
        Map<String, String> formFields = new HashMap<>();
        for (FileItem item : fileItems) {
            if (item.isFormField()) {
                formFields.put(item.getFieldName(), item.getString("UTF-8"));
            }
        }//map中读取数据
        PlayListDTO playListDTO = new PlayListDTO();
        playListDTO.setName(formFields.get("name"));
        //在session中获取userId
        HttpSession session = req.getSession();
        Integer userId=((UserDTO) session.getAttribute("userDTO")).getId();
        playListDTO.setUserId(userId);
        Result result = playListService.insertPlayList(playListDTO,fileItems);
        System.out.println(result);
        //返回结果
        resp.getWriter().write(JSONObject.toJSONString(result));
    }

    public void deletePlayList(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        System.out.println("deletePlayList...");
        //前端获取playListId
        Integer playListId = Integer.parseInt(req.getParameter("playListId"));
        //在session中获取userId
        HttpSession session = req.getSession();
        Integer userId=((UserDTO) session.getAttribute("userDTO")).getId();
        //调用service
        Result result=playListService.deletePlayList(userId,playListId);
        //返回结果
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JSONObject.toJSONString(result));
    }









}
